package com.heima.page.service;

import com.alibaba.fastjson.JSONArray;
import com.heima.common.exception.config.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class GeneratePageService {

  @Autowired
  private Configuration configuration;

  @Resource(name = "minIOFileStorageService")
  private FileStorageService fileStorageService;

  @Value("${file.oss.profix}")
  private String profix;

  @Autowired
  private ArticleFeign articleFeign;


  /**
     * 根据文章id生成文章静态页面
     * @param articleId
     */
  public void generateArticlePage(Long articleId) throws Exception {
    //1.获取文章内容
    ApArticleContent apArticleContent = articleFeign.findArticleContentById(articleId);
    if (apArticleContent != null && StringUtils.isNotBlank(apArticleContent.getContent())) {

      ApArticle apArticle = articleFeign.findArticleById(articleId);


      //2. 模板
      Template template = configuration.getTemplate("article.ftl");

      //3. 数据
      Map<String, Object> params = new HashMap<>();
      params.put("content", JSONArray.parseArray(apArticleContent.getContent()));
      params.put("article", apArticle);
      //apAuthorApUserId
      ApAuthor author = articleFeign.findApAuthorById(apArticle.getAuthorId());
      if (author==null||author.getUserId()==null){
        CustException.cust("文章作者不能为空 authorId:"+apArticle.getAuthorId());
      }
      Integer userId = author.getUserId();
      params.put("authorApUserId",userId);
      //4.生成静态文件
      StringWriter out = new StringWriter();
      template.process(params, out);
      InputStream is = new ByteArrayInputStream(out.toString().getBytes());

      //5.生成页面把html文件上传到minio中
      String fileUrl = fileStorageService.store(profix, apArticleContent.getArticleId() + ".html", "text/html", is);
      //6.修改ap_article表，保存static_url字段
      apArticle.setStaticUrl(fileUrl);
      articleFeign.updateArticleById(apArticle);
    }
  }

}